# import requests
# import base64
# from datetime import datetime

# # 百度API密钥
# ak = "QTL2lxFHDMOr7FbuAiZRkz8F"
# sk = "I6Y5h5BygSt1IEFPOO5488RXHeyfNfMu"

# def getToken():
#     """获取百度API访问令牌"""
#     host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}'
#     try:
#         response = requests.get(host)
#         response.raise_for_status()
#         return response.json()['access_token']
#     except requests.RequestException as e:
#         print(f"获取token失败: {e}")
#         return "error"

# def img_to_base64(file_path):
#     """将图片转换为base64编码"""
#     try:
#         with open(file_path, 'rb') as f:
#             base_64_data = base64.b64encode(f.read())
#             return base_64_data.decode()
#     except FileNotFoundError:
#         print(f"文件 {file_path} 未找到")
#         return None

# def get_person_num(path):
#     """获取图片中的人数"""
#     request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_num"
#     access_token = getToken()
#     if access_token == "error":
#         return None

#     img = img_to_base64(path)
#     if img is None:
#         return None

#     params = {
#         "image": img,
#         "show": "true"
#     }
#     request_url = request_url + "?access_token=" + access_token
#     headers = {'content-type': 'application/json'}

#     try:
#         response = requests.post(request_url, data=params, headers=headers)
#         response.raise_for_status()
#         result = response.json()
#         return result.get('person_num')
#     except requests.RequestException as e:
#         print(f"请求 {path} 时出错: {e}")
#         return None

# def calculate_crowd_density():
#     """计算各景点的人流量"""
#     # 景点对应的图片路径
#     scenes = {
#         "鹿苑": "test01.jpg",
#         "儿童动物园": "test02.jpg",
#         "非洲动物区": "test03.jpg",
#         "长颈鹿馆": "test04.jpg",
#         "猿猴馆": "test05.jpg",
#         "金丝猴馆": "test06.jpg",
#         "科普馆": "test07.jpg",
#         "两栖爬行馆": "test08.jpg",
#         "企鹅乐园": "test09.jpg",
#         "火烈鸟馆": "test10.jpg"
#     }
    
#     # 计算每个景点的人流量
#     crowd_data = {}
#     for name, img_path in scenes.items():
#         # 获取图片中的实际人数
#         person_num = get_person_num(img_path)
#         crowd_data[name] = person_num if person_num is not None else 50

#     return crowd_data

# if __name__ == "__main__":
#     # 测试代码
#     crowd_data = calculate_crowd_density()
#     for attraction, crowd in crowd_data.items():
#         print(f"{attraction}: {crowd}人")
import requests
import base64
import json
from datetime import datetime
import random

ak = "QTL2lxFHDMOr7FbuAiZRkz8F"
sk = "I6Y5h5BygSt1IEFPOO5488RXHeyfNfMu"

# 缓存文件路径
CACHE_FILE = "crowd_cache.json"
CACHE_DURATION = 3600  # 缓存有效期（秒）

def load_cache():
    """加载缓存数据"""
    try:
        with open(CACHE_FILE, 'r') as f:
            data = json.load(f)
            # 检查缓存是否过期
            if datetime.now().timestamp() - data['timestamp'] < CACHE_DURATION:
                return data['crowd_data']
    except (FileNotFoundError, json.JSONDecodeError, KeyError):
        pass
    return None

def save_cache(crowd_data):
    """保存数据到缓存"""
    cache_data = {
        'timestamp': datetime.now().timestamp(),
        'crowd_data': crowd_data
    }
    with open(CACHE_FILE, 'w') as f:
        json.dump(cache_data, f)

def getToken():
    host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}'
    try:
        response = requests.get(host)
        response.raise_for_status()
        return response.json()['access_token']
    except requests.RequestException as e:
        print(f"获取 token 失败: {e}")
        return "error"

def img_to_base64(file_path):
    try:
        with open(file_path, 'rb') as f:
            base_64_data = base64.b64encode(f.read())
            base_64 = base_64_data.decode()
            return base_64
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到")
        return None

def get_file_content_as_base64(path):
    """获取图片base64编码"""
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode()

def detect_crowd(image_path):
    """调用百度API检测人流量"""
    try:
        url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_num"
        
        # 获取access token
        token_url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}"
        token_response = requests.get(token_url)
        access_token = token_response.json().get('access_token')
        
        # 准备请求参数
        params = {
            "image": get_file_content_as_base64(image_path)
        }
        
        # 发送请求
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        request_url = f"{url}?access_token={access_token}"
        response = requests.post(request_url, data=params, headers=headers)
        
        # 解析结果
        result = response.json()
        if 'person_num' in result:
            return result['person_num']
        return 0
        
    except Exception as e:
        print(f"检测人流量时出错：{str(e)}")
        return 0

def generate_crowd_density():
    """生成所有景点的人流量数据"""
    try:
        crowd_densities = []
        # 检测每个景点的照片
        for i in range(1, 11):
            image_path = f"test{i:02d}.jpg"  # test01.jpg, test02.jpg, ...
            crowd = detect_crowd(image_path)
            crowd_densities.append(crowd)
        return crowd_densities
    except Exception as e:
        print(f"生成人流量数据时出错：{str(e)}")
        return []

def calculate_crowd_density():
    """计算各景点的人流量"""
    # 先尝试从缓存加载数据
    cached_data = load_cache()
    if cached_data:
        return cached_data

    try:
        # 获取新的人流量数据
        crowd_densities = generate_crowd_density()
        
        # 确保有足够的数据
        if not crowd_densities or len(crowd_densities) < 10:
            print("警告：使用默认人流量数据")
            crowd_densities = [12, 21, 165, 32, 60, 90, 72, 196, 316, 55]
        
        # 格式化数据
        crowd_data = {
            "鹿苑": crowd_densities[0],
            "儿童动物园": crowd_densities[1],
            "非洲动物区": crowd_densities[2],
            "长颈鹿馆": crowd_densities[3],
            "猿猴馆": crowd_densities[4],
            "金丝猴馆": crowd_densities[5],
            "科普馆": crowd_densities[6],
            "两栖爬行馆": crowd_densities[7],
            "企鹅乐园": crowd_densities[8],
            "火烈鸟馆": crowd_densities[9]
        }
        
        # 保存到缓存
        save_cache(crowd_data)
        return crowd_data
        
    except Exception as e:
        print(f"计算人流量密度时出错：{str(e)}")
        # 返回默认数据
        default_data = {
            "鹿苑": 12,
            "儿童动物园": 21,
            "非洲动物区": 165,
            "长颈鹿馆": 32,
            "猿猴馆": 60,
            "金丝猴馆": 90,
            "科普馆": 72,
            "两栖爬行馆": 196,
            "企鹅乐园": 316,
            "火烈鸟馆": 55
        }
        save_cache(default_data)
        return default_data

if __name__ == "__main__":
    # 运行一次并保存结果
    crowd_data = calculate_crowd_density()
    print("人流量数据已更新并缓存：")
    for attraction, crowd in crowd_data.items():
        print(f"{attraction}: {crowd}人")